<template>
  <div class="relative inline-block text-left"
    ref="select">
    <div>
      <button type="button"
        class="dropdown inline-flex items-center w-full justify-center bg-gray-2100 px-3 text-sm font-medium text-gray-1000 hover:bg-purple-100 hover:bg-purple-1300 hover:text-white to-show-options"
        :class="{'border':hasBorder, 'border-gray-1300':hasBorder, 'shadow-sm':hasBorder}"
        aria-expanded="true"
        aria-haspopup="true"
        @click="showOptions">
        <span class="whitespace-nowrap truncate">{{resetLabel()}}</span>
        <svg class="-mr-1 ml-2 h-5 w-5"
          viewBox="0 0 20 20"
          fill="currentColor"
          aria-hidden="true"
          :class="{show:targetObj.isShowOptions}">
          <path fill-rule="evenodd"
            d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z"
            clip-rule="evenodd" />
        </svg>
      </button>
    </div>

    <div class="absolute left-0 z-10 mt-2 min-w-full origin-top-right rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none optionsMax"
      role="menu"
      aria-orientation="vertical"
      tabindex="-1"
      v-show="targetObj.isShowOptions">
      <div class="py-1"
        role="none">
        <common-link :path="$route.params.lang?$route.path.replace(`/${$route.params.lang}`,''):$route.path"
          :query="resetSortPath(tItem)"
          v-for="(tItem,key) in targetObj.options"
          :key="key"
          class="text-gray-1000 block px-4 py-2 text-sm duration-100 hover:text-purple-1300 whitespace-nowrap go-sort-change"
          :class="{'text-purple-1300': resetSortStatus(tItem),'font-semibold': resetSortStatus(tItem),'hover:opacity-90': resetSortStatus(tItem) }">
          {{$t('sortBy')}}{{$t(tItem.label)}}
        </common-link>

        <div class="px-4">
          <el-divider class="my-3"></el-divider>
        </div>

        <common-link :path="$route.params.lang?$route.path.replace(`/${$route.params.lang}`,''):$route.path"
          :query="resetDirectionPath(tItem)"
          v-for="(tItem,key) in directionOptions"
          :key="'direction-'+key"
          class="text-gray-1000 block px-4 py-2 text-sm duration-100 hover:text-purple-1300 whitespace-nowrap flex items-center group go-direction-change"
          :class="{'text-purple-1300': resetDirectionStatus(tItem),'font-semibold': resetDirectionStatus(tItem),'hover:opacity-90': resetDirectionStatus(tItem) }">
          <svg-icon class="mr-1 text-gray-1500 group-hover:text-purple-1300"
            :class="{'text-purple-1300': resetDirectionStatus(tItem),'hover:opacity-90': resetDirectionStatus(tItem) }"
            :iconName='tItem.icon'></svg-icon>
          <span>{{$t(tItem.label)}}</span>
        </common-link>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CommonSelect',
  props: {
    targetObj: {
      type: Object,
      default: () => ({}),
    },
    directionOptions: {
      type: Array,
      default: () => [],
    },
    //是否有边框
    hasBorder: {
      type: Boolean,
      default: true,
    },
    //是否有边框
    selectType: {
      type: String,
      default: 'attributes',
    },
  },
  watch: {
    '$route.query': {
      handler(val) {
        this.targetObj.isShowOptions = false
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    document.addEventListener('click', this.handleClick)
  },
  methods: {
    handleClick(event) {
      if (this.$refs.select) {
        let self = this.$refs.select.contains(event.target)
        if (!self) {
          this.targetObj.isShowOptions = false
        }
      }
    },
    showOptions() {
      this.targetObj.isShowOptions = !this.targetObj.isShowOptions
    },

    /* 排序 */
    resetSortPath(tItem) {
      let newPath = { ...this.$route.query }
      if (newPath.sort && tItem.val === newPath.sort) {
        delete newPath.sort
      } else {
        newPath.sort = tItem.val
      }

      for (let key in newPath) {
        if (newPath[key] === null || newPath[key] === '') {
          delete newPath[key]
        }
      }

      return { ...newPath }
    },

    /* 顺序、倒序 */
    resetDirectionPath(tItem) {
      let newPath = { ...this.$route.query }
      if (newPath.direction && tItem.val === newPath.direction) {
        delete newPath.direction
      } else {
        newPath.direction = tItem.val
      }

      for (let key in newPath) {
        if (newPath[key] === null || newPath[key] === '') {
          delete newPath[key]
        }
      }

      return { ...newPath }
    },
    resetDirectionStatus(tItem) {
      let direction = this.$route.query.direction
      if (
        (direction && tItem.val === direction) ||
        (!direction && tItem.val === 'desc')
      ) {
        return true
      } else {
        return false
      }
    },
    resetLabel() {
      let sortVal = this.$route.query.sort
      let directionVal = this.$route.query.direction

      let sortLabel
      let directionLabel
      if (sortVal) {
        let sIndex = this.targetObj.options.findIndex((item) => {
          return item.val === sortVal
        })

        if (sIndex >= 0) {
          sortLabel = this.$i18n.t(this.targetObj.options[sIndex].label)
        } else {
          sortLabel = this.$i18n.t(this.targetObj.options[0].label)
        }
      } else {
        sortLabel = this.$i18n.t(this.targetObj.options[0].label)
      }

      if (directionVal) {
        let dIndex = this.directionOptions.findIndex((item) => {
          return item.val === directionVal
        })
        if (dIndex >= 0) {
          directionLabel = this.$i18n.t(this.directionOptions[dIndex].label)
        }
      }

      if (directionLabel && sortLabel) {
        return `${directionLabel}: ${sortLabel}`
      } else if (sortLabel) {
        return `${this.$i18n.t('sortBy')}${sortLabel}`
      } else if (directionLabel) {
        return `${directionLabel}`
      }
    },
    resetSortStatus(tItem) {
      let sort = this.$route.query.sort
      if (
        (sort && tItem.val === sort) ||
        (!sort && tItem.val === 'recommended_at')
      ) {
        return true
      } else {
        return false
      }
    },
    /* 排序 end */
  },
  beforeDestroy() {
    document.removeEventListener('click', this.handleClick)
  }
}
</script>
<style lang='scss' scoped>
.dropdown {
  height: 34px;
  border-radius: 17px;
  svg {
    transition: 0.2s;
    &.show {
      transform: rotate(180deg);
    }
  }
}
</style>
